<template>
  <view>
    <view style="margin-top: 40px;padding-bottom:80px ;" v-if="!payOrderShow">
      <!-- 标题 -->
      <view class="cu-bar bg-white">
        <view class="action sub-title">
          <text class="text-xl text-bold text-blue">我的订单</text>
          <text class="text-ABC text-blue">order</text>
        </view>
      </view>
      <!-- 搜索框 -->
      <view class="cu-bar search bg-white">
        <view class="search-form round">
          <text class="cuIcon-search"></text>
          <input @focus="InputFocus" @blur="InputBlur" :adjust-position="false" type="text"
            placeholder="搜索订单类型、订单号" confirm-type="search"></input>
        </view>
        <view class="action">
          <button class="cu-btn bg-green shadow-blur round" @click="searchOrder">搜索</button>
        </view>
      </view>
      <!-- 订单导航栏 -->
      <scroll-view scroll-x class="bg-white nav">
        <view class="flex text-center">
          <view class="cu-item flex-sub" :class="index==TabCur?'text-orange cur':''"
            v-for="(item,index) in orderListTitle" :key="index" @tap="tabSelect" :data-id="index">
            {{item}}
          </view>
        </view>
      </scroll-view>
      <!-- 加载框 -->
      <view class="cu-load load-modal" v-if="loadModal">
        <!-- <view class="cuIcon-emojifill text-orange"></view> -->
        <image src="/static/logo.png" mode="aspectFit"></image>
        <view class="gray-text">加载中...</view>
      </view>
      <!-- 订单信息区域 -->
      <form>
        <view class="order-item" v-for="(item,index) in orderListByType" :key="index" @longpress="longpress(item)"
          @click="checkOrderInfo(item)">
          <view class="cu-form-group margin-top">
            <view class="order-title text-df text-gray">
              <view class="cu-tag round light"
                :class="[item.type==='代取送'?'bg-orange':'',item.type==='代购'?'bg-olive':'',item.type==='万能帮'?'bg-blue':'']">
                {{item.type}}
              </view>
              <!-- <view class='cu-avatar round' :style="{'background-image': `url(${checkPic(item.userId)})`}"></view> -->
              <text class="text-gray" style="margin-left: 10px;">id:{{item._id}}</text>
            </view>
            <text class="text-sm" :class="item.state==='待支付'? 'text-red':'text-green'">
              {{item.finished?'已完成':item.state}}
            </text>
          </view>
          <!-- 代取送订单 -->
          <view class="order-detail" v-show="item.type==='代取送'">
            <view class="order-detail-title text-df ">物品类型: <text class="text-gray"
                style="margin-left: 20px;">{{item.goodsInfo.goodsType}}</text> </view>
            <view class="order-detail-title text-df ">物品重量: <text class="text-gray"
                style="margin-left: 20px;">{{item.goodsInfo.goodsWeight}}kg</text></view>
            <view class="order-detail-title text-df ">跑腿距离: <text class="text-gray"
                style="margin-left: 20px;">{{item.distance}}</text>
            </view>
          </view>
          <!-- 代购订单 -->
          <view class="order-detail" v-show="item.type==='代购'">
            <view class="order-detail-title text-df ">代购商品:
              <text class="text-gray" style="margin-left: 20px;">{{item.goodsInfo.goodsDetail}}</text>
            </view>
            <view class="order-detail-title text-df ">是否指定店铺: <text class="text-gray"
                style="margin-left: 20px;">{{JSON.stringify(item.shopAddress) === '{}' ? '否':'是'}}</text>
            </view>
          </view>
          <!-- 万能帮 -->
          <view class="order-detail flex" v-show="item.type==='万能帮'">
            <view class="order-detail-title text-df ">投稿:
              <text class="text-gray" style="margin-left: 20px;">{{item.helpInfo.content}}</text>
            </view>
          </view>
        </view>
        <!-- 删除对话框 -->
        <view class="cu-modal" :class="modalName=='deleteShow'?'show':''">
          <view class="cu-dialog">
            <view class="cu-bar bg-white justify-end">
              <view class="action" @tap="hideModal">
                <text class="cuIcon-close text-red"></text>
              </view>
            </view>
            <view class="padding-xl text-lg">
              确认删除这个订单吗？
            </view>
            <view class="cu-bar bg-white justify-end">
              <view class="action">
                <button class="cu-btn bg-green " @tap="hideModal">取消</button>
                <button class="cu-btn bg-red margin-left" @click="confirmDeleteOrder">确定</button>
              </view>
            </view>
          </view>
        </view>
      </form>

      <!-- 设置默认背景 -->
      <view class="default-img" v-show="orderListByType.length===0">
        <image class="shop-icon-tupianbeijing" mode="aspectFill"></image>
      </view>
    </view>
    <!-- 支付 -->
    <pay-order v-else :orderId="orderId" :price="price"></pay-order>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  const db = uniCloud.database();
  export default {
    name: "order",
    data() {
      return {
        TabCur: 0,
        scrollLeft: 0,
        loadModal: false,
        orderListTitle: ['全部', '待支付', '待接单', '进行中', '已完成'],
        InputBottom: 0,
        searchValue: '',
        //存储不同title订单信息
        orderListByType: [],
        modalName: null,
        //要删除的订单id
        deleteOrderId: '',
        //支付订单组件显示
        payOrderShow: false,
        //未支付的订单id
        orderId: '',
        //未支付的订单的price
        price: 0,
        imgList: []
      };
    },
    mounted() {
      this.selectOrderList()
    },
    methods: {
      ...mapMutations('m_user', ['updateOrderList']),
      // async checkPic(userId) {
      //   const {
      //     result: res
      //   } = await db.collection('my_user').where({
      //     _id: userId
      //   }).get()
      //   console.log(res.data[0].avatarUrl);
      //   return res.data[0].avatarUrl;
      // },
      //查询所有订单列表信息 事件回调
      async selectOrderList() {
        //先判断用户是否登录 携带token
        if (!this.token) return uni.$showMsg('请先登录！')
        this.loadModal = true;
        const {
          result: res
        } = await db.collection('my_order').where({
          userId: this.userinfo._id
        }).get()

        this.updateOrderList(res.data)
        this.orderListByType = this.orderList
        this.loadModal = false
      },
      //删除订单
      longpress(item) {
        this.modalName = 'deleteShow'
        this.deleteOrderId = item._id
      },
      //确实删除订单 按钮
      async confirmDeleteOrder() {
        console.log(this.deleteOrderId);
        const {
          result: res
        } = await db.collection('my_order').where({
          _id: this.deleteOrderId
        }).remove()
        console.log(res);
        if (res.deleted === 1) {
          uni.$showMsg('删除成功！')
          this.modalName = null
          this.deleteOrderId = ''
          this.selectOrderList()
        } else {
          uni.$showMsg('删除失败！')
        }

      },
      //查看订单详情页面 传递订单信息
      checkOrderInfo(item) {
        if (item.state === '待支付') {
          this.payOrder(item);
          return;
        }
        if (getCurrentPages().length >= 10) { //判断当前页面栈是否大于等于10.如果大于或等于就使用wx.redirectTo来跳转页面，清除当前页面栈
          uni.redirectTo({
            url: '/subpkg/order-detail/order-detail?orderId=' + JSON.stringify(item._id),
          })
        } else {
          uni.navigateTo({
            url: '/subpkg/order-detail/order-detail?orderId=' + JSON.stringify(item._id),
          })
        }
      },
      hideModal(e) {
        this.modalName = null
      },
      //订单类型导航切换
      tabSelect(e) {
        this.TabCur = e.currentTarget.dataset.id;
        this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
        switch (this.TabCur) {
          case 1:
            this.orderListByType = this.orderList.filter(item => !item.finished && item.state === '待支付')
            break;
          case 2:
            this.orderListByType = this.orderList.filter(item => !item.finished && item.state === '待接单')
            break;
          case 3:
            this.orderListByType = this.orderList.filter(item => !item.finished && item.state === '进行中')
            break;
          case 4:
            this.orderListByType = this.orderList.filter(item => item.finished)
            break;
          default:
            this.orderListByType = this.orderList
            break;
        }
      },
      InputFocus(e) {
        this.InputBottom = e.detail.height
      },
      InputBlur(e) {
        this.searchValue = e.detail.value
        this.InputBottom = 0
      },
      //搜索按钮事件
      searchOrder() {
        if (this.searchValue === '') {
          this.orderListByType = this.orderList
        } else {
          const tempOrderList = this.orderList.filter((item) => {
            return item.type === this.searchValue || item._id === this.searchValue
          })
          if (tempOrderList.length===0) {
            uni.$showMsg('订单不存在！')
          } else {
            this.orderListByType = tempOrderList
          }
        }
      },
      //支付订单事件
      payOrder(item) {
        console.log(item);
        this.orderId = item._id
        this.price = item.price
        this.payOrderShow = true
      },
    },
    computed: {
      ...mapState('m_user', ['userinfo', 'orderList', 'token']),
    }
  }
</script>

<style lang="scss">
  .order-title {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .order-detail {
    background-color: #ffffff;
    padding: 1rpx 30rpx;
    display: flex;
    min-height: 100rpx;
    justify-content: space-between;
    flex-direction: column;
    border: 1px solid silver;

    .order-detail-title {
      margin: 10px 0;
    }
  }

  .default-img {
    width: 120px;
    height: 120px;
    margin: 150px auto;
    overflow: hidden;
  }
</style>